module mbox.Conf;

import 
	mbox.Types;

struct MyConf {
	static char[]	AppDir ;
	static char[]	AppIni ;
	static char[]	AppDb ;
	
	static char[]	host	= null  ;
	static char[]	ip	= "127.0.0.1" ;
	static int		port	= 25 ;
	
	static int		try_delay	= 6 ;
	static int		try_max	= 4 ;
	static char[]	only_user ;
	
	static void Init() {
		wchar[256]   app_tmp ;
		int i	= GetModuleFileNameW(null, app_tmp.ptr, app_tmp.length);
		scope app_path	= Utf.toString( app_tmp[0..i] );
		foreach(ref c ; app_path) if( c == '\\' ) c = '/' ;
		
		AppDir	= app_path[0..rfind(app_path, '/') ].dup ;
		AppIni	= app_path.dup ;
		AppDb	= app_path[0..$-1].dup ;
		
		AppIni[$-1]	= 'i';
		AppIni[$-2]	= 'n';
		AppIni[$-3]	= 'i';
		
		AppDb[$-1]	= 'b';
		AppDb[$-2]	= 'd';
		
		FIXED_INFO fi ;
		uint j		= fi.sizeof;
		auto ret	= GetNetworkParams(&fi, &j);
		if( ret !is 0 ){
			Stdout.formatln("GetNetworkParams: `{}`",  SysError.lookup(ret) );
			/*
			Cin.get;
			exit(1);
			*/
		}
		
		char[] local_name, local_domain	= null ;
		foreach(int _i, c; fi.HostName){
			if( c is 0 ) {
				local_name		= fi.HostName[ 0 .. _i] .dup ;
				break;
			}
		}
		
		foreach(int _i, c; fi.DomainName){
			if( c is 0 ) {
				local_domain	= fi.DomainName[ 0 .. _i] .dup ;
				break;
			}
		}
		if( local_name !is null ){
			if( local_domain is null ){
				host	= local_name.dup ;
			}else{
				host	= (local_name ~ "." ~ local_domain).dup   ;
			}
		}
		
		
		
		if( !Pth.exists( AppIni ) ){
			Stdout("missing file `")(AppIni)("`\n").flush;
			Cin.get;
			exit(1);
		}
		
		scope fs	= new File( AppIni ) ;
		scope ls	= new Lines!(char)(fs);
		foreach(int _li, _ln; ls) {
			char[] ln	= Txt.trim(_ln);
			if( ln.length is 0 || ln[0] is ';' || ln[0] is '#' ){
				continue ;
			}
			i	= find(ln, '=' );
			if( i is ln.length ){
				continue ;
			}
			char[] key	= Txt.trim(ln[ 0 .. i ]) ;
			char[] val	= Txt.trim(ln[  i +1 .. $]) ;
			if( val.length < 1 || key.length < 1 ){
				continue ;
			}
			if( key == "host" ) {
				host	= val.dup ;
			}else if( key == "ip" ) {
				ip	= val.dup ;
			}else if( key == "port" ) {
				port	= Int.parse(val);
				if( port < 23 || port > 65534 ){
					port	= 25 ;
				}
			}else if( key == "try_delay" ) {
				try_delay	= Int.parse(val);
				if( try_delay < 4 || try_delay > 600 ){
					try_delay	= 6 ;
				}
			}else if( key == "try_max" ) {
				try_max	= Int.parse(val);
				if( try_max < 1 || try_delay > 60 ){
					try_max	= 4 ;
				}
			}else if( key == "only_user" ) {
				only_user	= val.dup ;
			}
		}
		
		bool isBreak	= false ;
		if( host is null || host.length is 0 ){
			Stdout("missing host in ")(AppIni)("\n");
			isBreak	= true ;
		}
		if( isBreak ){
			Stdout.flush;
			Cin.get;
			exit(1);
		}
		
		Stdout.formatln("SMTP Server Host name is {} ", host);
	}
}


